<template>
  <div class="user">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="手机号">
        <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker
          v-model="time"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="users"
      style="width: 100%">
      <el-table-column
        prop="id"
        label="用户ID"
      >
      </el-table-column>
      <el-table-column
        prop="name"
        label="头像"
      >
        <template slot-scope="scope">
          <el-avatar size="small" :src="scope.row | formatAvatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="用户名"
      >
      </el-table-column>
      <el-table-column
        prop="phone"
        label="手机号"
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="注册时间"
      >
        <template slot-scope="scope">
          <span>{{scope.row.createTime | formatDate}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
      >
        <template slot-scope="scope">
          <div class="status" :class="{
            'status-danger': scope.row.status === 'DISABLE',
            'status-success': scope.row.status === 'ENABLE'
          }"></div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="操作"
        width="180">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 'ENABLE'" type="text" @click="forbidden(scope.row)">禁用</el-button>
          <el-button type="text" @click="allotRole(scope.row)">分配角色</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrapper">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="searchForm.currentPage"
        :disabled="loading"
        :page-sizes="[10, 15, 20]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog title="分配角色" :visible.sync="visible" width="30%">
      <el-form :model="handleForm">
        <el-form-item prop="name">
          <el-select v-model="handleForm.ids" multiple placeholder="请选择" :style="inputWidth">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" :disabled="loading"  @click="saveOrUpdateRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getUserPages, forbidUser } from '@/services/user'
import {
  getAllRole,
  getCurrentRoleInfo,
  allocateUserRoles
} from '@/services/role'

export default Vue.extend({
  name: 'UserIndex',
  data () {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker: any) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker: any) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker: any) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      time: '',
      inputWidth: {
        width: '400px'
      },
      handleForm: {
        ids: []
      },
      searchForm: {
        phone: '',
        currentPage: 1,
        pageSize: 20,
        endCreateTime: '',
        startCreateTime: ''
      },
      total: 0,
      users: [],
      loading: false,
      visible: false,
      roles: [],
      currentUserInfo: {}
    }
  },
  created () {
    this.loadUserPages()
  },
  methods: {
    async loadCurrentRole (row: any) {
      const { data } = await getCurrentRoleInfo(row.id)
      const ids: any[] = []
      data.data.forEach((item: any) => {
        ids.push(item.id)
      })
      this.handleForm.ids = ids as never[]
    },
    allotRole (row: any) {
      this.loadAllRole()
      this.loadCurrentRole(row)
      this.visible = true
      this.currentUserInfo = row
    },
    async loadAllRole () {
      const { data } = await getAllRole()
      this.roles = data.data
    },
    onSubmit () {
      this.searchForm.startCreateTime = this.time ? this.time[0] : ''
      this.searchForm.endCreateTime = this.time ? this.time[1] : ''
      this.loadUserPages()
    },
    async loadUserPages () {
      this.loading = true
      const { data } = await getUserPages(this.searchForm)
      this.loading = false
      this.total = data.data.total
      this.users = data.data.records
    },
    handleSizeChange (val: number) {
      this.searchForm.pageSize = val
      this.searchForm.currentPage = 1
      this.loadUserPages()
    },
    handleCurrentChange (val: number) {
      this.searchForm.currentPage = val
      this.loadUserPages()
    },
    async saveOrUpdateRole () {
      this.loading = true
      try {
        await allocateUserRoles({
          userId: (this.currentUserInfo as any).id,
          roleIdList: this.handleForm.ids
        })
        this.$message.success('操作成功')
        this.loadUserPages()
      } catch (e) {
        console.log(e)
      }
      this.loading = false
      this.visible = false
      this.handleForm = {
        ids: []
      }
    },
    async forbidden (row: any) {
      try {
        await forbidUser({
          userId: row.id
        })
        this.$message.success('操作成功')
        this.loadUserPages()
      } catch (e) {
        console.log(e)
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.status {
  display: inline-block;
  cursor: pointer;
  width: .875rem;
  height: .875rem;
  vertical-align: middle;
  border-radius: 50%;
  &.status-danger {
    background-color: #ff6b6b;
  }
  &.status-success {
    background-color: #51cf66;
  }
}
.pagination-wrapper {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
